<script setup lang="ts">
import {useUserStore} from '@/stores/user'
import {reactive, ref} from "vue";
import {ElMessage} from "element-plus";
import router from "@/router";

const userStore = useUserStore()

//表单响应式数据定义
let registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phonenumber: ''
})
let registerRef = ref()
// 验证密码⼀致性
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输⼊密码'))
  } else if (value !== registerForm.password) {
    // console.log(registerForm.password, value)
    callback(new Error('两次输⼊密码不⼀致!'))
  } else {
    callback()
  }
}

// 表单校验规则
let registerRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, validator: validateConfirmPassword, trigger: 'blur'}
  ],
  email: [
    {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'},
  ],
  phonenumber: [
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'},
  ]
}
let loading = ref(false) // 注册按钮加载状态

let handleRegister = async () => {
  /**
   * 表单验证函数
   * 该函数用于触发表单验证，并在验证完成后执行回调函数
   * @param {Function} callback - 验证完成后的回调函数
   * @returns {void}
   */
  if (!registerRef.value) return  // 验证表单
  await registerRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    registerRef.value.validate(async () => {
      // 验证完成后输出表单数据
      // console.log(registerForm)

      try {
        loading.value = true // 显示加载状态
        // 发送注册表单信息
        let result = await userStore.register(
            {
              username: registerForm.username, // 用户名
              password: registerForm.password, // 密码
              email: registerForm.email, // 邮箱
              phonenumber: registerForm.phonenumber // 手机号
            }
        )
        // console.log("result:", result)
        if (result.success) {
          ElMessage.success('注册成功')
          // 跳转到首页
          router.push('/login')
        } else {
          ElMessage.error(result.message)
        }
      } catch (error: any) {
        ElMessage.error(error.message)
      } finally {
        loading.value = false // 隐藏加载状态
      }

    })
  })
}

let handleLogin = () => {
  router.push('/login') // 跳转到登录页面
}
</script>

<template>
  <div class="register">
    <el-form
        ref="registerRef"
        class="register-form"
        :model="registerForm"
        :rules="registerRules"
    >
      <h3 class="title">用户注册</h3>
      <el-form-item prop="username">
        <el-input
            type="text"
            size="large"
            auto-complete="off"
            placeholder="请输入用户名"
            prefix-icon="User"
            v-model="registerForm.username"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
            type="password"
            size="large"
            auto-complete="off"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            v-model="registerForm.password"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input
            type="password"
            size="large"
            auto-complete="off"
            placeholder="请确认密码"
            prefix-icon="Lock"
            show-password
            v-model="registerForm.confirmPassword"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="email">
        <el-input
            type="email"
            size="large"
            auto-complete="off"
            placeholder="请输入邮箱（可选）"
            prefix-icon="Message"
            v-model="registerForm.email"
        >
        </el-input>
      </el-form-item>
      <el-form-item prop="phonenumber">
        <el-input
            type="text"
            size="large"
            auto-complete="off"
            placeholder="请输入手机号（可选）"
            prefix-icon="Phone"
            v-model="registerForm.phonenumber"
        >
        </el-input>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button
            :loading="loading"
            size="large"
            type="primary"
            style="width:100%;"
            @click="handleRegister"
        >
          <span>{{ loading ? '注册中...' : '注 册' }}</span>
        </el-button>
      </el-form-item>
      <div class="login-link">
        <span>已有账号？</span>
        <el-link type="primary" @click="handleLogin">
          立即登录
        </el-link>
      </div>
    </el-form>
  </div>
</template>


<style scoped lang="scss">
.register {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url("@/assets/images/bg.png");
  background-size: cover;

  .register-form {
    border-radius: 6px;
    background: #ffffff;
    width: 400px;
    padding: 25px 25px 25px 25px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .title {
      margin: 0px auto 30px auto;
      text-align: center;
      color: #707070;
      font-size: 20px;
      font-weight: bold;
    }

    .el-input {
      height: 40px;

      :deep(.el-input__wrapper) {
        padding: 0 15px;
      }
    }

    .login-link {
      text-align: center;
      margin-top: 20px;
      font-size: 14px;
      color: #606266;
    }
  }
}
</style>
